//
//  YNSStartViewController.m
//  HNBaseProject
//
//  Created by TR on 2024/7/19.
//

#import "YNSStartViewController.h"
#import "DCTextView.h"
#import "YNSRuningVC.h"
#import "YNSPayVC.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import <AppsFlyerLib/AppsFlyerLib.h>
#import "YNSApplePayVC.h"
@interface YNSStartViewController ()<MxNavigationViewDelegate,TZImagePickerControllerDelegate>

@property (nonatomic, strong) MxPublicNav *nav;
@property(nonatomic,strong)UIScrollView*bgScrollView;
@property(nonatomic,strong)UIImageView*topImageV;
@property(nonatomic,strong)UIImageView*tipImageV;
@property(nonatomic,strong)UILabel*tLab;
@property(nonatomic,strong)UILabel*cLab;
@property(nonatomic,strong)DCTextView*contentTV;
@property(nonatomic,strong)UIButton*comfireBtn;
@property(nonatomic,strong)UIButton*AIBtn;

@property(nonatomic,copy)NSString*imgUrl;

@end

@implementation YNSStartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self createUI];
    if (self.pic_url)
    {
        self.imgUrl = [NSString stringWithFormat:@"%@",self.pic_url];
        [self.topImageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.pic_url]]];
        self.contentTV.content = self.titleStr;
    }
    [self getinfo];
}

- (void)createUI {
    
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = @"";//@"制作";
    self.nav.delegate = self;
    self.nav.line.hidden = NO;
    self.nav.backButton.hidden = YES;
    self.nav.rightBtn.hidden = NO;
    [self.nav.rightBtn setImage:[UIImage imageNamed:@"home_back"] forState:UIControlStateNormal];
    [self.view addSubview:self.nav];
    
    self.bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kNavBarHeight, kScreenW, kScreenH-kNavBarHeight)];
    self.bgScrollView.backgroundColor = [UIColor whiteColor];
    self.bgScrollView.contentSize = CGSizeMake(kScreenW, kRealValue(308)+382);
    
    [self.view addSubview:self.bgScrollView];
    
    self.topImageV = [[UIImageView alloc]initWithFrame:CGRectMake(23, 15, kScreenW-46, kRealValue(308))];
    self.topImageV.image = [UIImage imageNamed:@"zz_photo"];
    self.topImageV.contentMode = UIViewContentModeScaleAspectFill;
    self.topImageV.clipsToBounds = YES;
    self.topImageV.userInteractionEnabled = YES;
    WEAKSELF;
    [self.topImageV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf takePhoto];
    }]];
    [self.bgScrollView addSubview:self.topImageV];
//    [self.topImageV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.offset(15);
//        make.left.offset(23);
//        make.right.offset(-23);
//        make.height.offset(kRealValue(308));
//    }];
    
//    self.tipImageV = [[UIImageView alloc]initWithFrame:CGRectMake(23, CGRectGetMaxY(self.topImageV.frame)+35, 19, 19)];
//    self.tipImageV.image = [UIImage imageNamed:@"zz_tips"];
//    [self.bgScrollView addSubview:self.tipImageV];
//    [self.tipImageV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.topImageV.mas_bottom).offset(35);
//        make.left.offset(23);
//        make.width.height.offset(19);
//    }];
    
    self.tLab = [[UILabel alloc]initWithFrame:CGRectMake(23, CGRectGetMaxY(self.topImageV.frame)+23, 100, 25)];
    self.tLab.text = NSLocalizedString(@"关键词", nil);//@"关键词";
    self.tLab.textColor = [UIColor colorWithHexString:@"#000000"];
    self.tLab.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    [self.bgScrollView addSubview:self.tLab];
//    [self.tLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.topImageV.mas_bottom).offset(23);
//        make.left.offset(34);
//    }];
    
    self.cLab = [[UILabel alloc]initWithFrame:CGRectMake(23, CGRectGetMaxY(self.tLab.frame)+10, kScreenW-50, 18)];
    self.cLab.text= NSLocalizedString(@"输入生成动画的关键词", nil);//@"";
    self.cLab.font = [UIFont systemFontOfSize:13];
    self.cLab.textColor = [UIColor colorWithHexString:@"#9A9A9A"];
    [self.bgScrollView addSubview:self.cLab];
//    [self.cLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.tipImageV.mas_bottom).offset(0);
//        make.left.offset(23);
//    }];
    
    self.contentTV = [[DCTextView alloc] initWithFrame:CGRectMake(23, CGRectGetMaxY(self.cLab.frame)+15, kScreenW-46, 151)];
    self.contentTV.placeholder = NSLocalizedString(@"请输入您的描述...", nil);;
    self.contentTV.placeholderColor = [UIColor colorWithHexString:@"#AFB6BB"];
    self.contentTV.backgroundColor = [UIColor colorWithHexString:@"#EFF3F6"];
    self.contentTV.textColor = [UIColor colorWithHexString:@"#333333"];
    self.contentTV.font = [UIFont systemFontOfSize:14];
    self.contentTV.maxLength = 200;
    self.contentTV.maxWordShow = YES;
    self.contentTV.layer.masksToBounds = YES;
    self.contentTV.layer.cornerRadius = 5;
    [self.bgScrollView addSubview:self.contentTV];
//    [self.contentTV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.cLab.mas_bottom).offset(15);
//        make.left.offset(23);
//        make.right.offset(-23);
//        make.height.offset(151);
//    }];
    
//    self.comfireBtn = [[UIButton alloc] initWithFrame:CGRectMake(23, CGRectGetMaxY(self.contentTV.frame)+22, kScreenW-46, 42)];
//    [self.comfireBtn setTitle:@"确认" forState:UIControlStateNormal];
//    [self.comfireBtn setTitleColor:[UIColor colorWithHexString:@"#1D8EFF"] forState:UIControlStateNormal];
//    self.comfireBtn.backgroundColor = [UIColor whiteColor];
//    self.comfireBtn.layer.masksToBounds = YES;
//    self.comfireBtn.layer.cornerRadius = 21;
//    self.comfireBtn.layer.borderColor = [UIColor colorWithHexString:@"#1D8EFF"].CGColor;
//    self.comfireBtn.borderWidth = 1;
//    [self.comfireBtn addTarget:self action:@selector(comfrieClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.bgScrollView addSubview:self.comfireBtn];
//    [self.comfireBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.contentTV.mas_bottom).offset(22);
//        make.left.offset(23);
//        make.right.offset(-23);
//        make.height.offset(42);
//    }];
    
    self.AIBtn = [[UIButton alloc] initWithFrame:CGRectMake(23, CGRectGetMaxY(self.contentTV.frame)+10, kScreenW-46, 42)];
    [self.AIBtn setTitle:NSLocalizedString(@"制作", nil) forState:UIControlStateNormal];
    [self.AIBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.AIBtn.layer.masksToBounds = YES;
    self.AIBtn.layer.cornerRadius = 21;
    [self.AIBtn addTarget:self action:@selector(aiClick) forControlEvents:UIControlEventTouchUpInside];
    [self.bgScrollView addSubview:self.AIBtn];
//    [self.AIBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.comfireBtn.mas_bottom).offset(10);
//        make.left.offset(23);
//        make.right.offset(-23);
//        make.height.offset(42);
//    }];
    
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0, 0, kScreenW-46, 42);
    gl.startPoint = CGPointMake(1, 0.45);
    gl.endPoint = CGPointMake(0, 0.5);
    gl.colors = @[(__bridge id)[UIColor colorWithHexString:@"#1D8EFF"].CGColor, (__bridge id)[UIColor colorWithHexString:@"#3BD5C5"].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    [self.AIBtn.layer addSublayer:gl];
}
#pragma mark ---MxNavigationViewDelegate-----
- (void)rightTap {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)leftTap {
    
}

#pragma mark-----ai-----
- (void)aiClick {
    if(self.imgUrl.length==0){
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"请选择图片", nil)];
        return;
    }
    if (self.contentTV.text.length==0)
    {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"请输入关键词", nil)];
        return;
    }
    //统计
    [[AppsFlyerLib shared]  logEvent: AFEventContentView withValues: @{
        AFEventParamContentId: @"1",
        AFEventParamContentType:@"制作视频"
    }];
    
    [SVProgressHUD show];
    WEAKSELF;
    [[DCHttpClient shareClient] requestWithPath:@"api/video.video/add" params:@{@"image_url":self.imgUrl,@"user_prompt":self.contentTV.text} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * dict = [responseObject mj_JSONObject];
        if([dict[@"code"] intValue]==1){
            YNSRuningVC*vc = [[YNSRuningVC alloc]init];
            vc.video_id = [NSString stringWithFormat:@"%@",dict[@"data"][@"video_id"]];
            vc.sureLeave = ^{
                [weakSelf reloadView];
            };
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else if ([dict[@"code"] intValue]== -1){
            YNSApplePayVC *payVC = [[YNSApplePayVC alloc]init];
            [weakSelf.navigationController pushViewController:payVC animated:YES];
        }
        else {
            [SVProgressHUD showInfoWithStatus:dict[@"msg"]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (void)reloadView {
    self.imgUrl = @"";
    self.topImageV.image = [UIImage imageNamed:@"zz_photo"];
    self.contentTV.content = @"";
}

#pragma mark----拍照------
-(void)takePhoto{
    TZImagePickerController * picker = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    picker.allowPickingVideo = NO;
    picker.allowTakeVideo =NO;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (photos.count>0)
    {
        [self uploadImgWith:[photos firstObject]];
    }
}

#pragma mark-----上传图片------
-(void)uploadImgWith:(UIImage*)img {
    WEAKSELF;
    [[DCHttpClient shareClient]requestUploadWithPath:@"api/upload/image" image:img fileName:@"file" progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            NSDictionary * dict = [responseObject mj_JSONObject];
            if([dict[@"code"] intValue]==1){
                weakSelf.imgUrl = [NSString stringWithFormat:@"%@",dict[@"data"][@"uri"]];
                [weakSelf.topImageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",dict[@"data"][@"uri"]]]];
            }
            else {
//                [SVProgressHUD showWithStatus:dict[@"msg"]];
            }
        } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
        }];
}

#pragma mark-------获取个人信息---------
-(void)getinfo {
    WEAKSELF;
    [[DCHttpClient shareClient] requestWithPath:@"api/user/center" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if([dict[@"code"] intValue]==1){
//            [weakSelf.AIBtn setTitle:[NSString stringWithFormat:@"%@：%@",NSLocalizedString(@"AI自动生成", nil),dict[@"data"][@"buy"]] forState:UIControlStateNormal];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}
@end
